﻿using System;
using Castle.DynamicProxy;

namespace AspectMap.StandardAspects
{
    public class RetryAttributeHandler : AttributeHandler
    {
        public override Action<IInvocation> Surround(Action<IInvocation> invocation, Attribute sourceAttribute)
        {
            if (!(sourceAttribute is RetryAttribute))
                throw new ArgumentException("Unable to handle retries for attribute '" + sourceAttribute.GetType() + "'.");

            RetryAttribute attribute = (RetryAttribute)sourceAttribute;

            return i =>
            {
                for (int count = 1; count <= attribute.MaxTries; count++)
                {
                    try
                    {
                        invocation(i);
                        return;
                    }
                    catch (Exception ex)
                    {
                        if (ex.GetType() != attribute.TargetException || count == attribute.MaxTries)
                            throw;
                    }
                }
            };
        }
    }
}
